package com.example.simple.work.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
public class FileUploadController {
    @Value("${file.upload-dir}")
    private String uploadDir; // 注入配置文件中的上传目录路径

    @GetMapping("/files")
    @CrossOrigin
    public ResponseEntity<List<String>> listFiles() {
        String uploadDir = "D:/simple_work/upload"; // 你的上传目录路径
        File dir = new File(uploadDir);
        if (!dir.exists() || !dir.isDirectory()) {
            return ResponseEntity.notFound().build();
        }
        String[] files = dir.list();
        if (files == null) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(Arrays.asList(files));
    }

    @PostMapping("/upload")
    @CrossOrigin
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        System.out.println("文件上传开始");

        try {
            // 获取文件名
            String originalFileName = file.getOriginalFilename();
            System.out.println("获取文件名：" + originalFileName);

            if (originalFileName == null || originalFileName.isEmpty()) {
                System.out.println("上传文件为空，请选择文件后再次上传。");
                return "上传文件为空，请选择文件后再次上传。";
            }

            // 提取基础文件名（不包括扩展名）和文件后缀名
            String baseName = originalFileName.substring(0, originalFileName.lastIndexOf("."));
            String fileExtension = originalFileName.contains(".") ? originalFileName.substring(originalFileName.lastIndexOf(".")) : "";
            System.out.println("基础文件名：" + baseName);
            System.out.println("文件后缀名：" + fileExtension);

            // 确保自定义目录存在
            File uploadDirectory = new File(uploadDir);
            if (!uploadDirectory.exists()) {
                uploadDirectory.mkdirs(); // 创建目录，包括必要的但不存在的父目录
            }

            // 构建文件存储路径
            String uniqueFileName = baseName + fileExtension;
            String filePath = uploadDir + File.separator + uniqueFileName;

            // 将文件保存到指定路径，如果文件存在则覆盖
            File destinationFile = new File(filePath);
            file.transferTo(destinationFile);
            System.out.println("文件上传成功：");
            return "文件上传成功，文件路径：" + filePath;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传失败：");
            return "文件上传失败：" + e.getMessage();
        }
    }
}
